package com.cskaoyan.market.admin.service.impl;

import com.cskaoyan.market.admin.service.MarketStorageService;
import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.db.domain.MarketStorageExample;
import com.cskaoyan.market.db.mapper.MarketStorageMapper;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.util.List;

public class MarketStorageServiceImpl implements MarketStorageService {
    @Override
    public List<MarketStorage> getList(String page, String limit, String key, String name, String sort, String order) {
        //获取session和映射
        SqlSession session = MyBatisUtil.getSession();
        MarketStorageMapper storageMapper = session.getMapper(MarketStorageMapper.class);

        //获取查询条件和查询对象
        MarketStorageExample storageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = storageExample.createCriteria();
        if (!StringUtils.isEmpty(key)) {
            criteria.andKeyEqualTo(key);
        }
        if (!StringUtils.isEmpty(name)) {
            String values = "%" + name + "%";
            criteria.andNameLike(values);
        }

        //设定排序规则和分页
        storageExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));

        //根据查询对象获取数据库的数据返回给前端响应
        List<MarketStorage> result = storageMapper.selectByExample(storageExample);

        //事务的关闭和提交
        session.commit();
        session.close();

        return result;
    }

    @Override
    public MarketStorage updateStorageName(String name, String id) {
        //获取session和映射
        SqlSession session = MyBatisUtil.getSession();
        MarketStorageMapper storageMapper = session.getMapper(MarketStorageMapper.class);
        //获取表格的实体数据
        //根据ID获取需要改变的数据库数据.
        MarketStorage marketStorage = storageMapper.selectByPrimaryKey(Integer.valueOf(id));
        marketStorage.setName(name);
        marketStorage.setUpdateTime(LocalDateTime.now());
        //把修改完的数据写入数据库
        storageMapper.updateByPrimaryKey(marketStorage);
        //事务的关闭和提交
        session.commit();
        session.close();
        //返回响应数据
        return marketStorage;
    }

    @Override
    public void deleteStorage(String id) {

        SqlSession session = MyBatisUtil.getSession();
        MarketStorageMapper mapper = session.getMapper(MarketStorageMapper.class);
        mapper.deleteByPrimaryKey(Integer.valueOf(id));

        session.commit();
        session.close();

    }
}
